<template>
    <div class="scratch-card">
        <canvas ref="canvasRef" class="scratch-card_canvas"></canvas>
    </div>
</template>
<script lang="ts" name="AgScratchCard" setup>
import { onMounted, onUnmounted, ref } from 'vue';

const canvasRef = ref<HTMLCanvasElement | null>(null);
let ctx:any = null;
let isDrawing = false;
// let lastX = 0;
// let lastY = 0;
// let hue = 0;
// let direction = true;
const initCanvas = () => {
    const canvas = canvasRef.value
    if (!canvas) { return; }
    ctx = canvas.getContext('2d');
    if (!ctx) { return; }
    // ctx.strokeStyle = '#BADA55';
    // ctx.lineJoin = 'round';
    // ctx.lineCap = 'round';
    // ctx.lineWidth = 100;
    // ctx.globalCompositeOperation = 'multiply';
    // canvas!.addEventListener('mousedown', (e) => {
    //     isDrawing = true;
    //     [lastX, lastY] = [e.offsetX, e.offsetY];
    // });
    // canvas!.addEventListener('mousemove', draw);
    // canvas!.addEventListener('mouseup', () => isDrawing = false);
    // canvas!.addEventListener('mouseout', () => isDrawing = false);
    
    // 刮奖区域
    ctx.fillStyle = '#888';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
// 遮罩层
    ctx.fillStyle = '#f00';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    canvas.addEventListener('mousedown', handleStart);
    canvas.addEventListener('mousemove', handleMove);
    canvas.addEventListener('mouseup', handleEnd);
    // canvas.addEventListener('mouseout', () => isDrawing = false);
    canvas.addEventListener('touchstart', handleStart);
    canvas.addEventListener('mousemove', handleMove);
    canvas.addEventListener('touchend', handleEnd);
    
}
const handleEnd=(e:any)=>{
    console.log('end',e)
    isDrawing = false;
}
const handleMove=(e:any)=>{
    console.log('move',e)
    if (isDrawing) { 
        // ctx.lineTo(e.clientX, e.clientY); 
        // ctx.stroke(); 
        ctx.clearRect(e.offsetX, e.offsetY,10, 10); // x和y参数定义了要清除的矩形区域的左上角的位置，width和height参数则定义了要清除的矩形区域的宽度和高度
    }
}
const handleStart=(e:any)=>{
    console.log('start',e)
    isDrawing = true;
    ctx.beginPath();
    // ctx.moveTo(e.offsetX, e.offsetY);
    ctx.moveTo(e.clientX, e.clientY);
}
onMounted(() => {
    initCanvas();
});
onUnmounted(() => {
   const canvas = canvasRef.value
   if (!canvas) { return; }
    canvas.removeEventListener('mousedown', handleStart);
    canvas.removeEventListener('mousemove', handleMove);
    canvas.removeEventListener('mouseup', handleEnd);
    // canvas.removeEventListener('mouseout', () => isDrawing = false); 
    canvas.removeEventListener('touchstart', handleStart);
    canvas.removeEventListener('mousemove', handleMove);
    canvas.removeEventListener('touchend', handleEnd);
});
</script>
<style lang="scss" scoped>
.scratch-card{
    position: relative;
    width: 500px;
    height: 200px;
}
.scratch-card_canvas{
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}
</style>